<template>
  <eip-modal
    v-if="modal.width != null && modal.height != null"
    :width="modal.width"
    :height="modal.height"
    :position="modal.position"
    :visible="visible"
    :id="options.zeroCodeId ? options.zeroCodeId : 'zeroCodeId'"
    :title="modal.title"
    :maskClosable="modal.maskClosable"
    :zIndex="modal.zIndex"
    @close="cancel"
  >
    <template slot="title">
      <worksheet-title
        v-if="options.mode == eipZeroCodeWorkSheetMode.edit"
        :rowId="rowId"
        :rowIds="options.rowIds"
        @change="rowChange"
      ></worksheet-title>
    </template>
    <template slot="body">
      <a-spin :spinning="loading">
        <slot name="header"> </slot>
        <section>
          <a-skeleton :loading="loading">
            <k-form-build
              ref="kfb"
              v-if="!loading"
              :dynamicData="dynamicData"
              :defaultValue="defaultValue"
              :formValue="formValue"
              :value="publicJson"
              :disabled="disabled"
              :worksheet="{
                zeroCodeId: options.zeroCodeId,
                mode: options.mode,
                rowId: rowId,
                from: options.from,
              }"
              @change="handleChange"
              @complete="desingerComplate"
            />
          </a-skeleton>
        </section>
      </a-spin>
    </template>

    <template slot="footer">
      <worksheet-button
        v-if="settingJson"
        :options="options"
        :systemZeroCode="systemZeroCode"
        :systemZeroCodeValue="formValue"
        @save="save"
        @reloadData="buttonReloadData"
      ></worksheet-button>
    </template>
  </eip-modal>
</template>

<script>
import { mapGetters } from "vuex";
import {
  findById,
  businessData,
  only,
  businessDataById,
  fileCorrelationId,
  serialNoCreate,
  findCorrelationDefaultAdd,
} from "@/services/system/zerocode/run/edit";
import { newGuid } from "@/utils/util";
import { getAuthorization } from "@/utils/request";
import { VxeUI } from "vxe-pc-ui";
import worksheetTitle from "./components/worksheet/title";
import worksheetButton from "./components/worksheet/button";
export default {
  components: { worksheetTitle, worksheetButton },
  name: "worksheet",
  computed: {
    ...mapGetters("account", ["user", "zeroCode"]),
  },
  data() {
    return {
      title: "", //标题
      modal: {
        width: null,
        height: null,
        zIndex: 1000,
        position: {
          top: null,
          left: "center",
        },
        maskClosable: false,
      },
      disabled: false,
      dynamicData: {}, //数据
      defaultValue: {}, //默认值
      formValue: {}, //表单值
      publicJson: {},
      settingJson: null,
      loading: false, //等待框loading
      complete: false, //是否加载完成
      systemZeroCode: {}, //当前配置信息
      rowId: this.options.rowId,
      changeKeys: [], //改变Key集合
    };
  },

  props: {
    //隐藏显示
    visible: {
      type: Boolean,
      default: false,
    },

    //配置
    options: {
      type: Object,
      default: () => ({
        //低代码Id
        zeroCodeId: {
          type: String,
        },
        //业务Id
        rowId: {
          type: String,
        },
        //所有业务Id,上一页下一页使用
        rowIds: {
          type: Array,
        },
        //模式add新增，edit更新
        mode: {
          type: String,
        },
        //来源参数（只有从关联记录控件点击新增才出现）
        from: {
          zeroCodeId: null, //工作表
          key: null, //来源控件(用于区分双向关联才解析默认绑定)
          rowId: null, //来源数据RowId,从列表上来时为多个，逗号分割
          button: null, //来源按钮Id,有值则表示从按钮点击来
        },
      }),
    },
  },
  watch: {
    visible: {
      handler: function (newVal, oldVal) {
        this.complete = false;
      },
      deep: true,
    },
  },
  created() {
    this.$nextTick(function () {
      this.init();
    });
  },
  methods: {
    /**
     * 初始化设计器
     */
    async init() {
      let that = this;
      that.loading = true;
      VxeUI.loading.open();
      var systemZeroCodeData = await findById(that.options.zeroCodeId);
      if (systemZeroCodeData.code === that.eipResultCode.success) {
        that.systemZeroCode = systemZeroCodeData.data;
      } else {
        that.$message.error("获取配置错误");
      }
      this.modal.title = that.systemZeroCode.name;
      if (that.systemZeroCode.publicJson) {
        this.initPublicJson();
        this.initUploadConfig();
      }
      if (that.systemZeroCode.settingJson) {
        this.initSettingJson();
      }
      await this.find();
      that.loading = false;
      VxeUI.loading.close();
    },

    /**
     * 查询数据
     */
    async find() {
      let that = this;
      that.defaultValue = {};
      that.formValue = {};
      if (that.options.mode == this.eipZeroCodeWorkSheetMode.edit) {
        await that.initEditData();
      } else if (that.options.mode == this.eipZeroCodeWorkSheetMode.button) {
        //是否选择的多个
        let button = this.options.from.button;
        if (
          button.form.target ==
            this.eipZeroCodeFormSettingButtonFormTarget.now &&
          button.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
        ) {
          if (
            that.options.from.rowId &&
            that.options.from.rowId.split(",").length == 1
          ) {
            that.rowId = that.options.from.rowId;
            await that.initEditData();
          }
        }
        //当前记录，填写关联
        else if (
          button.form.target ==
            this.eipZeroCodeFormSettingButtonFormTarget.now &&
          button.form.write ==
            this.eipZeroCodeFormSettingButtonFormWrite.correlation
        ) {
          var value = {};
          var columnJson = JSON.parse(that.systemZeroCode.columnJson);
          for (let index = 0; index < columnJson.length; index++) {
            const item = columnJson[index];
            await that.setDefaultValue(item, value);
          }
          that.defaultValue = that.$utils.clone(value, true);
          that.formValue = that.$utils.clone(value, true);
        } else if (
          button.form.target ==
            this.eipZeroCodeFormSettingButtonFormTarget.correlation &&
          button.form.write == this.eipZeroCodeFormSettingButtonFormWrite.field
        ) {
          that.rowId = that.options.from.rowId;
          await that.initEditData();
        }
      } else {
        var value = {};
        var columnJson = JSON.parse(that.systemZeroCode.columnJson);
        for (let index = 0; index < columnJson.length; index++) {
          const item = columnJson[index];
          await that.setDefaultValue(item, value);
        }
        that.defaultValue = that.$utils.clone(value, true);
        that.formValue = that.$utils.clone(value, true);
      }
    },

    /**
     * 加载编辑页面数据
     */
    async initEditData() {
      let that = this;
      var result = await businessDataById({
        zeroCodeId: that.options.zeroCodeId,
        id: that.rowId,
      });
      if (result.code == that.eipResultCode.success) {
        await that.setFormValue(result);
        that.modal.title += ":" + result.data[that.publicJson.config.title];
      } else {
        that.$message.destroy();
        that.$message.error(result.msg);
      }
    },

    /**
     * 初始化自动化编辑页面,若有则会覆盖对应字段
     */
    initPublicJson() {
      let that = this;
      var publicJson = JSON.parse(that.systemZeroCode.publicJson);
      this.initModal(publicJson);

      this.initOnlyRules(publicJson);
      that.publicJson = publicJson;
    },

    /**
     * 保存流数据
     */
    save(saveData) {
      let that = this;
      this.$refs.kfb
        .getData()
        .then(async (res) => {
          var data = that.getFormValue(res);
          if (data.values == "[]") {
            that.$message.error("未检测到数据变化,请修改后重试");
            return false;
          }
          that.$loading.show({ text: that.eipMsg.saveLoading });
          businessData(data).then(async function (result) {
            that.$loading.hide();
            that.$message.destroy();
            if (result.code == that.eipResultCode.success) {
              that.$message.success(result.msg);
              that.$emit("ok", result);
              if (that.options.mode == that.eipZeroCodeWorkSheetMode.add) {
                that.reserveFormValue(saveData);
              } else if (
                that.options.mode == that.eipZeroCodeWorkSheetMode.button
              ) {
                that.cancel();
              }
            } else {
              that.$message.error(result.msg);
            }
          });
        })
        .catch((err) => {
          that.$message.destroy();
          that.$loading.hide();
        });
    },

    /**
     * 保留表单内容
     */
    reserveFormValue(data) {
      let that = this;
      let submit = "submit";
      let submitContinue = "submitContinue";
      var submitAfterClose = 1;
      var submitAfterCloseNext = 2;
      //点击提交按钮
      let type = data.type;
      if (type == submit) {
        //直接关闭
        if (that.settingJson.form.submitAfter == submitAfterClose) {
          that.cancel();
        } else if (that.settingJson.form.submitAfter == submitAfterCloseNext) {
          //清空数据
          that.$refs.kfb.reset();
        } else {
          //打开刚刚记录
          that.rowChange(that.rowId);
        }
      }

      //点击继续创建按钮
      if (type == submitContinue) {
        //直接关闭
        if (that.settingJson.form.submitContinueAfter == submitAfterClose) {
          that.cancel();
        } else if (that.settingJson.form.submitAfter == submitAfterCloseNext) {
          //继续创建,保留本次提交内容
          if (that.settingJson.form.submitContinueSaveData) {
            //显示“保留上次提交内容”选项，由用户决定是否保留  并且 用户勾选了
            //或者 无需询问，自动保留
            if (
              (that.settingJson.form.submitContinueSaveDataTip == 1 &&
                data.saveRetain) ||
              that.settingJson.form.submitContinueSaveDataTip == 2
            ) {
              //保留字段内容
              if (that.settingJson.form.submitContinueSaveDataType == 2) {
                that.$utils.objectEach(that.formValue, (item, key) => {
                  if (
                    !that.settingJson.form.submitContinueSaveDataTypeCustom.includes(
                      key
                    )
                  ) {
                    that.formValue[key] = undefined;
                  }
                });
                that.$refs.kfb.setData(that.formValue);
              }
            }
          } else {
            //清空数据
            that.$refs.kfb.reset();
          }
        } else {
          //打开刚刚记录
        }
      }
      this.rowId = newGuid();
    },

    /**
     * 获取提交数据
     */
    getFormValue() {
      let that = this;
      let values = [];
      var options = that.$refs.kfb.getOptions();
      if (
        [
          that.eipZeroCodeWorkSheetMode.button,
          that.eipZeroCodeWorkSheetMode.edit,
        ].includes(this.options.mode)
      ) {
        options = options.filter((f) => that.changeKeys.includes(f.key));
      }
      options
        .filter(
          (f) =>
            ![
              that.eipZeroCodeControl.text,
              that.eipZeroCodeControl.divider,
            ].includes(f.type)
        )
        .forEach((columnObj) => {
          var value = that.formValue[columnObj.key];
          var options = undefined;
          var array = [];
          switch (columnObj.type) {
            case that.eipZeroCodeControl.checkbox:
              options = columnObj.options.options;
              if (value) {
                value.map((m) => {
                  array.push(m);
                });
                values.push({
                  key: columnObj.key,
                  value: array.length > 0 ? JSON.stringify(array) : null,
                });
              }
              break;
            case that.eipZeroCodeControl.select:
              options = columnObj.options.options;
              if (columnObj.options.multiple && value) {
                value.map((m) => {
                  array.push(m);
                });
              } else {
                array.push(value);
              }
              values.push({
                key: columnObj.key,
                value: array.length > 0 ? JSON.stringify(array) : null,
              });
              break;
            case that.eipZeroCodeControl.radio:
              options = columnObj.options.options;
              if (value) {
                array.push(value);
                values.push({
                  key: columnObj.key,
                  value: array.length > 0 ? JSON.stringify(array) : null,
                });
              }
              break;
            case that.eipZeroCodeControl.correlation:
              if (value) {
                //单选
                if (
                  columnObj.options.type ==
                  that.eipZeroCodeControlCorrelationType.single
                ) {
                  array.push(value);
                } else {
                  //是否为表格模式
                  if (
                    columnObj.options.showType ==
                    that.eipZeroCodeControlCorrelationShowType.grid
                  ) {
                    value.map((m) => {
                      array.push(m.RowId);
                    });
                  } else {
                    value.map((m) => {
                      array.push(m);
                    });
                  }
                }
              }
              values.push({
                key: columnObj.key,
                value: JSON.stringify(array),
              });
              break;
            case that.eipZeroCodeControl.subtable:
              if (value) {
                value.forEach((fvitem) => {
                  //变成key,value数组
                  var arrayItem = [];
                  var keys = that.$utils.keys(fvitem);
                  keys
                    .filter((f) => f != "_X_ROW_KEY")
                    .forEach((kitem) => {
                      arrayItem.push({
                        key: kitem,
                        value: fvitem[kitem],
                      });
                    });
                  array.push({
                    rowId: arrayItem.filter((f) => f.key == "RowId")[0].value,
                    data: arrayItem,
                  });
                });
              }
              values.push({
                key: columnObj.key,
                value: JSON.stringify(array),
              });
              break;
            case that.eipZeroCodeControl.textCombination:
              break;
            case that.eipZeroCodeControl.otherField:
              break;
            case "treeSelect":
              break;
            case "cascader":
              break;
            case that.eipZeroCodeControl.district:
              options = columnObj.options.options;
              options = that.$utils.toTreeArray(options);
              options = options.filter((f) => value.includes(f.value));
              options.forEach((item) => {
                array.push({
                  label: item.label,
                  value: item.value,
                });
              });
              values.push({
                key: columnObj.key,
                value: array.length > 0 ? JSON.stringify(array) : null,
              });
              break;
            case that.eipZeroCodeControl.dictionary:
              if (value) {
                if (columnObj.options.dictionaryShowType == 2) {
                  values.push({
                    key: columnObj.key,
                    value: JSON.stringify([value]),
                  });
                }
                if (columnObj.options.dictionaryShowType == 3) {
                  values.push({
                    key: columnObj.key,
                    value: JSON.stringify(value),
                  });
                }
              }
              break;
            case that.eipZeroCodeControl.user:
            case that.eipZeroCodeControl.organization:
              break;
            case that.eipZeroCodeControl.map:
              values.push({
                key: columnObj.key,
                value: value,
              });
              break;
            case that.eipZeroCodeControl.uploadFile:
            case that.eipZeroCodeControl.uploadImg:
              values.push({
                key: columnObj.key,
                value: JSON.stringify(value),
              });
              break;
            case that.eipZeroCodeControl.serialNo:
              break;
            default:
              values.push({
                key: columnObj.key,
                value: value,
              });
              break;
          }
        });
      return {
        zeroCodeId: this.options.zeroCodeId,
        rowId: this.rowId,
        values: JSON.stringify(values),
      };
    },

    /**
     * 赋予表单值
     * @param {*} result
     */
    async setFormValue(result) {
      let that = this;
      var columnJson = JSON.parse(that.systemZeroCode.columnJson);
      for (let index = 0; index < columnJson.length; index++) {
        const item = columnJson[index];
        var value = result.data[item.key];
        switch (item.type) {
          case that.eipZeroCodeControl.select:
            if (value) {
              if (item.options.multiple) {
                result.data[item.key] = JSON.parse(value);
              } else {
                result.data[item.key] = JSON.parse(value)[0];
              }
            }
            break;
          case that.eipZeroCodeControl.checkbox:
            if (value) {
              result.data[item.key] = JSON.parse(value);
            }
            break;
          case that.eipZeroCodeControl.radio:
            if (value) {
              result.data[item.key] = JSON.parse(value)[0];
            }
            break;
          case that.eipZeroCodeControl.correlation:
            if (value) {
              if (
                item.options.type ==
                that.eipZeroCodeControlCorrelationType.single
              ) {
                result.data[item.key] = JSON.parse(value)[0];
              } else {
                result.data[item.key] = JSON.parse(value).map((m) => m);
              }
            }
            break;
          case that.eipZeroCodeControl.district:
            if (value) {
              result.data[item.key] = JSON.parse(value).map((m) => m.value);
            }
            break;
          case that.eipZeroCodeControl.uploadFile:
          case that.eipZeroCodeControl.uploadImg:
            var uploads = [];
            var fileResult = await fileCorrelationId(
              that.rowId + "|" + item.key
            );
            fileResult.forEach((upload, index) => {
              uploads.push({
                fileId: upload.fileId || "",
                type:
                  item.type == that.eipZeroCodeControl.uploadImg
                    ? "img"
                    : "file",
                name: upload.name,
                status: "done",
                uid: index,
                url: upload.path || "",
              });
            });
            result.data[item.key] = uploads;
            break;
          case that.eipZeroCodeControl.dictionary:
            if (value) {
              //单选
              if (item.options.dictionaryShowType == 2) {
                result.data[item.key] = JSON.parse(value)[0];
              }
              //复选
              if (item.options.dictionaryShowType == 3) {
                result.data[item.key] = JSON.parse(value);
              }
            }
            break;
          case that.eipZeroCodeControl.total:
            if (value) {
              result.data[item.key] = value;
            }
            break;
          case that.eipZeroCodeControl.formula:
            if (value) {
              result.data[item.key] = value;
            }
            break;
        }
      }
      //删除无用RowId字段
      delete result.data.RowId;
      that.defaultValue = that.$utils.clone(result.data);
      that.formValue = result.data;
    },

    /**
     * 获取所有上传控件
     */
    getOptionsByType(types) {
      var files = [];
      // 递归遍历控件树
      const traverse = (array) => {
        array.forEach((element) => {
          if (types.includes(element.type)) {
            files.push(element);
          }
          if (
            ["grid", "tabs", "selectInputList", "collapse"].includes(
              element.type
            )
          ) {
            // 栅格布局 and 标签页
            element.columns.forEach((item) => {
              traverse(item.list);
            });
          } else if (element.type === "card" || element.type === "batch") {
            // 卡片布局 and  动态表格
            traverse(element.list);
          } else if (element.type === "table") {
            // 表格布局
            element.trs.forEach((item) => {
              item.tds.forEach((val) => {
                traverse(val.list);
              });
            });
          }
        });
      };
      traverse(this.publicJson.list);
      return files;
    },

    /**
     * 默认值
     */
    async setDefaultValue(item, value) {
      let that = this;
      await that.setDefalutSerialNo(item, value);
      await that.setDefalutDistrict(item, value);
      await that.setDefalutCorrelation(item, value);
      await that.setDefalutRadio(item, value);
      await that.setDefalutCheckbox(item, value);
      await that.setDefalutInput(item, value);
      await that.setDefalutNumber(item, value);
    },

    /**
     * 初始化编码默认值
     */
    async setDefalutSerialNo(item, value) {
      let that = this;
      if (
        item.type == that.eipZeroCodeControl.serialNo &&
        item.options.loadDisplay
      ) {
        //编码
        var result = await serialNoCreate({
          rule: JSON.stringify(item.options.rule),
          loadDisplay: item.options.loadDisplay,
          userOccupation: item.options.userOccupation,
          zeroCodeId: that.options.zeroCodeId,
          key: item.key,
        });

        if (result.code == that.eipResultCode.success) {
          value[item.key] = result.data;
        }
      }
    },

    /**
     * 初始化省市区默认值
     */
    async setDefalutDistrict(item, value) {
      let that = this;
      if (item.type == that.eipZeroCodeControl.district) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.value:
            value[item.key] = item.options.defaultValue;
            break;
          case that.eipZeroCodeDefaultType.field:
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 初始化数字框默认值
     */
    async setDefalutNumber(item, value) {
      let that = this;
      if (
        item.options.defaultValueConfig &&
        item.type == that.eipZeroCodeControl.number
      ) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            //查询工作表
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
          case that.eipZeroCodeDefaultType.value:
            value[item.key] = item.options.defaultValue;
            break;
        }
      }
    },
    /**
     * 初始化文本框默认值
     */
    async setDefalutInput(item, value) {
      let that = this;
      if (
        item.options.defaultValueConfig &&
        item.options.defaultValueConfig.code &&
        (item.type == that.eipZeroCodeControl.input ||
          item.type == that.eipZeroCodeControl.textarea)
      ) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            //查询引用的字段
            var check = that.$utils.has(that.formValue, item.key);
            if (!check) {
              var keys = that.getDefaultCodeKeys(
                item.options.defaultValueConfig.code
              );
              if (keys.length > 0) {
                for (let index = 0; index < keys.length; index++) {
                  const kitem = keys[index];
                  //关联表
                  if (kitem.zeroCodeId) {
                  } else {
                    //当前表单
                    var columnJson = JSON.parse(that.systemZeroCode.columnJson);
                    var columnFind = that.$utils.find(
                      columnJson,
                      (f) => f.key == kitem.key
                    );
                    await that.setDefaultValue(columnFind, value);
                  }
                }
              }
            }

            let content = this.getDefaultCodeContent(
              item.options.defaultValueConfig.code,
              value
            );
            value[item.key] = content;
            if (check && that.$refs.kfb) {
              //重新赋予值
              that.formValue[item.key] = content;
              that.$refs.kfb.setData({
                [item.key]: content,
              });
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            //查询工作表
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     *获取代码先关联的Key
     * @param content
     */
    getDefaultCodeKeys(content) {
      //解析默认值
      let keys = [];
      const tempDiv = document.createElement("div");
      // 设置div的内容为HTML字符串
      tempDiv.innerHTML = content;
      // 查询所有的span标签
      const divs = tempDiv.querySelectorAll("div");
      for (let index = 0; index < divs.length; index++) {
        const div = divs[index];
        const span = div.querySelectorAll("span")[0];
        var parseData = JSON.parse(decodeURI(span.id));
        keys.push(parseData);
      }
      return keys;
    },
    /**
     * 获取带有代码值的内容
     * @param defaultValue
     */
    getDefaultCodeContent(content, value) {
      //解析默认值
      let that = this;
      const tempDiv = document.createElement("div");
      // 设置div的内容为HTML字符串
      tempDiv.innerHTML = content;
      // 查询所有的span标签
      const divs = tempDiv.querySelectorAll("div");
      divs.forEach((div) => {
        const span = tempDiv.querySelectorAll("span")[0];
        var parseData = JSON.parse(decodeURI(span.id));
        var key = parseData.key;
        switch (key) {
          case "CreateUserId":
            content = content.replaceAll(div.outerHTML, that.user.userId);
            break;
          case "CreateUserName":
            content = content.replaceAll(div.outerHTML, that.user.name);
            break;
          case "CreateOrganizationId":
            content = content.replaceAll(
              div.outerHTML,
              that.user.organizationId
            );
            break;
          case "CreateOrganizationName":
            content = content.replaceAll(
              div.outerHTML,
              that.user.organizationName
            );
            break;
          default:
            content = content.replaceAll(
              div.outerHTML,
              that.$utils.isUndefined(value[key]) ? "" : value[key]
            );
            break;
        }
      });
      return content;
    },

    /**
     * 初始化关联表默认值
     */
    async setDefalutCorrelation(item, value) {
      let that = this;
      if (item.type == that.eipZeroCodeControl.correlation) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.value:
          case that.eipZeroCodeDefaultType.field:
            //单选，并且选择有默认值
            if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.single &&
              item.options.defaultValueConfig.field.length > 0
            ) {
              value[item.key] = item.options.defaultValueConfig.field[0].key;
            } else if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.multiple &&
              item.options.defaultValueConfig.field.length > 0
            ) {
              value[item.key] = item.options.defaultValueConfig.field.map(
                (f) => f.key
              );
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            let result = await findCorrelationDefaultAdd({
              zeroCodeId: this.options.zeroCodeId,
              key: item.key,
            });
            if (result.code == that.eipResultCode.success) {
              value[item.key] = result.data.data.map((f) => f.RowId);
              that.dynamicData[item.key] = result;
            }
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 初始化单选默认值
     */
    async setDefalutRadio(item, value) {
      let that = this;
      if (item.type == that.eipZeroCodeControl.radio) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            var field = item.options.defaultValueConfig.field;
            //单选，并且选择有默认值
            if (field.length > 0) {
              if (field[0].key == "") {
                value[item.key] = field[0].value;
              }
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 初始化多选默认值
     */
    async setDefalutCheckbox(item, value) {
      let that = this;
      if (item.type == that.eipZeroCodeControl.checkbox) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            var field = item.options.defaultValueConfig.field;
            //单选，并且选择有默认值
            if (field.length > 0) {
              value[item.key] = field.map((m) => m.value);
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 赋值
     */
    kfbSetOptions(key, data) {
      if (this.complete) {
        this.$refs.kfb.options(key, data);
      }
    },

    /**
     * 初始化唯一规则验证
     */
    initOnlyRules(publicJson) {
      let that = this;
      var onlys = publicJson.list.filter((f) => f.options && f.options.only);
      onlys.forEach((item) => {
        item.rules.push({
          validator: (rule, value, callback) => {
            if (typeof value === "undefined" || value === "") {
              callback();
            } else {
              let param = {
                rowId: that.rowId,
                zeroCodeId: that.options.zeroCodeId,
                key: item.key,
                value: value,
              };
              only(param).then((result) => {
                if (result.code == 200) {
                  callback();
                } else {
                  callback(new Error("已存在相同" + item.label));
                }
              });
            }
          },
          trigger: "change",
        });
      });
    },

    /**
     * 值改变
     */
    async handleChange(value, key) {
      var that = this;
      var data = { value, key };
      that.formValue[data.key] = data.value;
      that.setOtherField(key);
      that.setChangeKey(key);
      await that.reloadDefaultValue(key);
    },
    /**
     * 添加改变Key
     */
    setChangeKey(key) {
      var find = this.$utils.find(this.changeKeys, (f) => f == key);
      if (find == null) {
        this.changeKeys.push(key);
      }
    },

    /**
     * 重新加载
     * @param key
     */
    async reloadDefaultValue(key) {
      //得到所有与当前控件先关联控件
      var that = this;
      var reloadDefaultValueParents = await that.reloadDefaultValueParents(key);
      for (let index = 0; index < reloadDefaultValueParents.length; index++) {
        const item = reloadDefaultValueParents[index];
        await that.setDefaultValue(item, that.formValue);
      }
    },

    /**
     * 重新加载
     * @param key
     */
    async reloadDefaultValueParents(key) {
      let that = this;
      let keys = [];
      var columnJson = JSON.parse(that.systemZeroCode.columnJson);
      // 递归遍历控件树
      const traverseParents = (key) => {
        for (let index = 0; index < columnJson.length; index++) {
          const element = columnJson[index];
          if (
            element.options.defaultValueConfig &&
            element.options.defaultValueConfig.code
          ) {
            var getDefaultCodeKeys = that.getDefaultCodeKeys(
              element.options.defaultValueConfig.code
            );
            //是否包含当前key
            if (getDefaultCodeKeys.map((m) => m.key).includes(key)) {
              keys.push(element);
              traverseParents(element.key);
            }
          }
        }
      };
      traverseParents(key);
      return keys;
    },

    /**
     * 关联字段
     */
    setOtherField(key) {
      //所有他表字段
      let that = this;
      var columnJson = JSON.parse(that.systemZeroCode.columnJson);
      var allOtherField = columnJson.filter((f) =>
        [this.eipZeroCodeControl.otherField].includes(f.type)
      );
      if (allOtherField.length > 0) {
        allOtherField.forEach((item) => {
          //查看关联数据源
          var fromKey = item.options.key;
          if (fromKey == key) {
            //设计字段
            var zeroCodeId = this.$utils.find(columnJson, (f) => f.key == key)
              .options.zeroCodeId;
            var field = item.options.field;

            var formKeyValue = that.formValue[key];
            if (formKeyValue) {
              if (zeroCodeId && field) {
                //获取关联记录
                businessDataById({
                  zeroCodeId: zeroCodeId,
                  id: that.formValue[key],
                }).then((result) => {
                  if (result.code == that.eipResultCode.success) {
                    var value = result.data[field];
                    that.formValue[item.key] = value;
                    that.$refs.kfb.setData({
                      [item.key]: value,
                    });
                  }
                });
              }
            } else {
              that.$refs.kfb.setData({
                [item.key]: null,
              });
            }
          }
        });
      }
    },

    /**
     * 表单加载完毕
     */
    async desingerComplate() {
      let that = this;
      that.complete = true;
      for (let key in this.dynamicData) {
        that.kfbSetOptions([key], this.dynamicData[key]);
      }
      this.initHidden();
    },

    /**
     * 初始化新增隐藏
     */
    initHidden() {
      let that = this;
      if (that.options.mode == that.eipZeroCodeWorkSheetMode.add) {
        if (this.systemZeroCode) {
          var columnJson = JSON.parse(this.systemZeroCode.columnJson);
          var hiddenAdds = columnJson.filter(
            (f) => f.options && f.options.hiddenAdd
          );
          var hides = [];
          hiddenAdds.forEach((item) => {
            hides.push(item.key);
          });

          this.$refs.kfb.hide(hides);
        }
      } else if (that.options.mode == that.eipZeroCodeWorkSheetMode.button) {
        var button = this.options.from.button;
        if (button) {
          //填写表单，并且填写内容为填写指定字段
          that.modal.title = button.name;
          if (
            button.action == that.eipZeroCodeFormSettingButtonAction.form &&
            button.form.write ==
              that.eipZeroCodeFormSettingButtonFormWrite.field
          ) {
            var columnJson = JSON.parse(this.systemZeroCode.columnJson);
            var hides = columnJson.map((m) => m.key);
            this.$refs.kfb.hide(hides);
            var writeKey = button.form.writeKey;
            that.$refs.kfb.show(writeKey.map((m) => m.key));
          } else if (
            button.action == that.eipZeroCodeFormSettingButtonAction.form &&
            button.form.write ==
              that.eipZeroCodeFormSettingButtonFormWrite.correlation
          ) {
            that.rowId = newGuid();
          }
        }
      }
    },

    /**
     * 删除children为空
     * @param {*} data
     */
    setChildrenTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children) {
          if (data[i].children.length < 1) {
            delete data[i].children;
          } else {
            this.setChildrenTreeData(data[i].children);
          }
        }
      }
      return data;
    },

    /**
     *初始化配置
     */
    initSettingJson() {
      let that = this;
      var settingJson = JSON.parse(that.systemZeroCode.settingJson);
      that.settingJson = settingJson;
    },

    /**
     * 初始化弹出框
     * @param publicJson
     */
    initModal(publicJson) {
      let config = publicJson.config;
      this.modal.maskClosable = config.maskClosable;
      this.modal.height = config.showFormHeight
        ? config.showFormHeight + config.showFormHeightUnit
        : 0;
      this.modal.width = config.showFormWidth + config.showFormWidthUnit;
      this.modal.zIndex = config.zIndex;
      if (!config.modalCentered) {
        this.modal.position.top = 30;
      }
    },

    /**
     * 初始化文件上传配置
     */
    initUploadConfig() {
      let that = this;
      var uploadFile = this.getOptionsByType([
        that.eipZeroCodeControl.uploadFile,
        that.eipZeroCodeControl.uploadImg,
      ]);
      uploadFile.forEach((item) => {
        if (!item.options.action) {
          item.options.action =
            window.SITE_CONFIG.eip.baseURL + "/system/file/uploadform";
        }

        item.options.data = JSON.stringify({
          correlationId: that.rowId + "|" + item.key,
          single: item.options.limit == 1,
          pdfShow: item.options.pdfShow,
        });
        var authorization = getAuthorization();
        item.options.headers = {
          Authorization: authorization,
        };
      });
    },

    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },

    /**
     * 解析filter，返回替换后表达式
     */
    analysisFilter(filter) {
      let that = this;
      let copyFilters = this.$utils.clone(filter, true);
      let filters = {
        groupOp: copyFilters.groupOp,
        rules: [],
        groups: [],
      };
      // 递归遍历控件树
      const traverseRule = (array, filters) => {
        array.forEach((element) => {
          switch (element.type) {
            case "correlation":
              filters.rules.push({
                field: element.field,
                op: element.op,
                data: that.analysisFilterData({
                  type: "correlation",
                  data: element.data,
                }),
              });

              break;
            default:
              filters.rules.push({
                field: element.field,
                op: element.op,
                data: that.analysisFilterData(element),
              });
              break;
          }
        });
      };
      traverseRule(copyFilters.rules, filters);

      const traverseGroup = (array, filters) => {
        array.forEach((element) => {
          var group = {
            groupOp: element.groupOp,
            rules: [],
            groups: [],
          };

          element.rules.forEach((rule) => {
            switch (rule.type) {
              case "correlation":
                if (rule.data.length > 0) {
                  var selectFilters = {
                    groupOp: "OR",
                    rules: [],
                  };
                  //循环值
                  rule.data.forEach((ditem) => {
                    selectFilters.rules.push({
                      field: rule.field.replace("_Txt", ""),
                      op: rule.op,
                      data: that.analysisFilterData({
                        type: "correlation",
                        data: ditem,
                      }),
                    });
                  });
                  group.groups.push(selectFilters);
                }
                break;
              default:
                group.rules.push({
                  field: rule.field,
                  op: rule.op,
                  data: that.analysisFilterData(rule),
                });
                break;
            }
          });

          filters.groups.push(group);

          if (element.groups.length > 0) {
            traverseGroup(element.groups, filters);
          }
        });
      };
      traverseGroup(copyFilters.groups, filters);
      return filters;
    },

    /**
     * 解析数据
     * @param {*} data
     */
    analysisFilterData(rule) {
      var that = this;
      var column = this.$utils.find(that.columnJson, (f) => f.key == rule.data);
      switch (rule.type) {
        case "input":
          return rule.data;
        case "correlationRecord":
          return this.formValue[column.key];
      }
    },

    /**
     * 数据改变
     * @param type
     */
    rowChange(rowId) {
      this.rowId = rowId;
      this.init();
    },

    /**
     * 重新加载数据
     */
    buttonReloadData(rowId) {
      this.rowChange(rowId);
      this.$emit("ok", {
        code: this.eipResultCode.success,
      });
    },

    /**
     *
     * @param button
     */
    buttonClick(button) {
      var that = this;
      //判断按钮类型
      that.worksheet.mode = that.eipZeroCodeWorkSheetMode.button;
      that.worksheet.from = {
        zeroCodeId: that.zeroCodeId, //工作表
        key: null, //来源控件(用于区分双向关联才解析默认绑定)
        rowId: that.rowId, //来源数据RowId,从列表上来时为多个
        button: button, //来源按钮,有值则表示从按钮点击来
      };
      that.worksheet.visible = true;
    },
  },
};
</script>

<style lang="less" scoped>
.eip-form-designer-container .content.toolbars-top,
.eip-form-build .content.toolbars-top {
  padding-bottom: 6px;
  height: calc(100% - 114px);
}

.eip-form-designer-container .operating-area,
.eip-form-build .operating-area {
  border-bottom: 1px solid #e8e8e8;
}

.eip-form-designer-container .content section {
  box-shadow: 0px 0px 1px 1px #e8e8e8;
}

.eip-form-designer-container .content aside {
  box-shadow: 0px 0px 1px 1px #e8e8e8;
}

.eip-form-build {
  overflow: auto;
  height: 100%;
  padding: 0px;
}
</style>
